package com.weishi.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;

public class ConfigUtil {
	private static final Logger logger = LoggerFactory.getLogger(ConfigUtil.class);
	private static Properties pp;
	static {
		try {
			ConfigUtil.load("config.properties");
		} catch (Exception e) {}
	}
	
	public static String getValue(String key) {
		return pp.getProperty(key);
	}
	
	public static String getValue(String key, String value) {
		try {
			String data = pp.getProperty(key);
			return data != null ? data : value;
		} catch (Exception e) {
			return value;
		}
	}
	
	public static void load(final String file) {
		URL url = ClassLoader.getSystemResource("");
		boolean result = false;
		if (url != null) {
			String classpath = url.getFile();
			String path = classpath + file;
			if (isFileExists(path)) {
				pp = readProperties(path);
				if (pp != null) {
					result = true;
					logger.info("properties path = {}", path);
				}
			}
		}

		if (!result) {
			InputStream ips = null;
			try {
				ips = ConfigUtil.class.getResourceAsStream(file.startsWith("/") == true ? file : "/" + file);
				pp = readProperties(ips);
				logger.info("properties path = {}", file);
			} catch (IOException e) {
				logger.warn("加载配置文件【{}】出错。", file);
			} finally {
				if (ips != null) {
					try {
						ips.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}

		LoggerUtils.getLogger().info(pp.toString());
	}

	private static Properties readProperties(final String filepath) {
		Properties pp = null;
		InputStream ips = null;
		try {
			pp = new Properties();
			ips = new FileInputStream(filepath);
			pp.load(ips);
		} catch (Exception e) {
			logger.error("加载配置文件【{}】出错！", filepath, e);
		} finally {
			if (ips != null) {
				try {
					ips.close();
				} catch (Exception e) {
				}
			}
		}
		return pp;
	}

	private static Properties readProperties(final InputStream ips) throws IOException {
		Properties pp = new Properties();
		pp.load(ips);
		return pp;
	}

	private static boolean isFileExists(final String path) {
		File file = new File(path);
		return file.exists();
	}
}
